import { useMemo, useState } from 'react';
import { Space, Input, Button, Typography, Card, Tag, Empty, Alert } from 'antd';
import { RightOutlined } from '@ant-design/icons';
import { useLocation } from 'react-router-dom';

function validateQueueWithTrace(
  values: string[]
): Array<{ index: number; value: string; isHead: boolean; isTail: boolean; pass: boolean }> {
  return values.map((v, i, arr) => ({
    index: i,
    value: v,
    isHead: i === 0,
    isTail: i === arr.length - 1,
    pass: v.length > 0,
  }));
}

export default function QueueVisualizer() {
  const [input, setInput] = useState('A,B,C');
  const [opValue, setOpValue] = useState('D');
  const location = useLocation();
  const isOverviewMode = location.pathname === '/queue';
  const isValidateMode = location.pathname.startsWith('/queue/validate');

  const values = useMemo(() => input.split(/[\s,]+/).filter(Boolean), [input]);
  const enqueue = () =>
    setInput((prev) => [...prev.split(/[\s,]+/).filter(Boolean), opValue].join(','));
  const dequeue = () =>
    setInput((prev) =>
      prev
        .split(/[\s,]+/)
        .filter(Boolean)
        .slice(1)
        .join(',')
    );

  const trace = useMemo(() => validateQueueWithTrace(values), [values]);
  const hasInvalid = useMemo(() => trace.some((t) => !t.pass), [trace]);

  return (
    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
      <Typography.Title level={2}>队列（Queue）可视化</Typography.Title>

      {isOverviewMode && (
        <Alert
          message="队列概述：定义与验证"
          description={
            <Typography.Paragraph style={{ marginBottom: 0 }}>
              定义：先进先出（FIFO）的线性结构，<Typography.Text strong>队头</Typography.Text>
              在左侧，<Typography.Text strong>队尾</Typography.Text>在右侧。
              <br />
              验证：基础检查为“元素非空字符串”，并标注队头与队尾位置以辅助理解。
            </Typography.Paragraph>
          }
          type="info"
          showIcon
        />
      )}

      {isValidateMode && (
        <Alert
          message="验证过程（队头/队尾标注）"
          description={
            <Typography.Paragraph style={{ marginBottom: 0 }}>
              逐元素检查是否为非空字符串，并标注队头（索引 0）与队尾（最后一个）。
            </Typography.Paragraph>
          }
          type={hasInvalid ? 'warning' : 'success'}
          showIcon
        />
      )}

      <Space>
        <Input
          allowClear
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="例如: A,B,C"
          style={{ width: 320 }}
        />
        <Input
          allowClear
          value={opValue}
          onChange={(e) => setOpValue(e.target.value)}
          placeholder="操作值，例如: D"
          style={{ width: 160 }}
        />
      </Space>
      <Space>
        <Button type="primary" onClick={enqueue}>
          入队（enqueue）
        </Button>
        <Button danger onClick={dequeue}>
          出队（dequeue）
        </Button>
      </Space>

      {isValidateMode && (
        <Card title="验证步骤（索引与队头/队尾）" size="small">
          {values.length === 0 ? (
            <Empty description="空队列" />
          ) : (
            <div style={{ display: 'grid', rowGap: 8 }}>
              {trace.map((t) => (
                <div key={t.index} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Tag color={t.pass ? 'green' : 'red'}>{t.pass ? '✓' : '✗'}</Tag>
                  <Typography.Text>
                    索引 <Typography.Text code>{t.index}</Typography.Text>，值{' '}
                    <Typography.Text code>{t.value}</Typography.Text>
                    {t.isHead && (
                      <Typography.Text style={{ marginLeft: 8 }} type="secondary">
                        （队头）
                      </Typography.Text>
                    )}
                    {t.isTail && (
                      <Typography.Text style={{ marginLeft: 8 }} type="secondary">
                        （队尾）
                      </Typography.Text>
                    )}
                  </Typography.Text>
                </div>
              ))}
            </div>
          )}
        </Card>
      )}

      <Card title="队头在左侧" size="small">
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {values.length === 0 ? (
            <Empty description="空队列" />
          ) : (
            values.map((v, i) => (
              <div key={`${v}-${i}`} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Tag color={i === 0 ? 'gold' : 'blue'} style={{ padding: '4px 10px' }}>
                  {v}
                </Tag>
                {i < values.length - 1 && <RightOutlined style={{ color: '#999' }} />}
              </div>
            ))
          )}
        </div>
      </Card>

      <Typography.Text type="secondary">
        提示：左侧为队头，enqueue 追加到末尾，dequeue 移除队头。
      </Typography.Text>
    </Space>
  );
}
